<template>
  <div class="data_content">
    <div class="data_c fl">
      <div class="data_c_1">
        <div id="contPar" class="contPar">
          <div id="page1" style="z-index:1">
            <div class="title0">车辆综合管控平台</div>
            <div class="title1">旅游、交通、危险品、校车、大数据</div>
            <div id="drag-container" ref="dragContainer" style="z-index: 1">
              <div id="spin-container" ref="spinContainer" :class="spinContainerClass">
                <img class="infoBtn" src="@/assets/picture/page1_0.png" />
                <img class="" src="@/assets/picture/page1_1.png" />
                <img class="" src="@/assets/picture/page1_2.png" />
                <img class="" src="@/assets/picture/page1_1.png" />
                <img class="" src="@/assets/picture/page1_2.png" />
              </div>
              <div id="ground" ref="ground"></div>
            </div>
            <img class="img3 png" src="@/assets/images/newdz.png" />
          </div>
        </div>
      </div>
      <div class="data_c_2 public">
        <div id="echart4" style="width: 100%; height: 100%; padding-top: 10px"></div>
        <div class="boxfoot"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue';

// 配置参数
const radius = 240; // 旋转半径
const autoRotate = true; // 是否自动旋转
const rotateSpeed = -60; // 旋转速度（秒/圈），负值表示反向旋转
const imgWidth = 120; // 图片宽度
const imgHeight = 170; // 图片高度

// DOM 引用
const dragContainer = ref<HTMLElement>();
const spinContainer = ref<HTMLElement>();
const ground = ref<HTMLElement>();

// 状态变量
const sX = ref(0);
const sY = ref(0);
const nX = ref(0);
const nY = ref(0);
const desX = ref(0);
const desY = ref(0);
const tX = ref(0);
const tY = ref(10);

// 计算旋转容器的类
const spinContainerClass = computed(() => {
  if (!autoRotate) return '';
  return rotateSpeed > 0 ? 'spin-animation' : 'spin-revert-animation';
});

// 定时器引用
let timer: NodeJS.Timeout | null = null;

// 检测移动设备
const isMobileDevice = (): boolean => {
  return 'ontouchstart' in window || navigator.maxTouchPoints > 0;
};

// 初始化函数
const init = (delayTime?: number): void => {
  if (!spinContainer.value) return;

  const images = spinContainer.value.getElementsByTagName('img');
  const elements = [...images];

  // 设置旋转容器尺寸
  spinContainer.value.style.width = `${imgWidth}px`;
  spinContainer.value.style.height = `${imgHeight}px`;

  // 设置地面阴影尺寸
  if (ground.value) {
    ground.value.style.width = `${radius * 3}px`;
    ground.value.style.height = `${radius * 3}px`;
  }

  // 设置每个元素的位置
  elements.forEach((element, index) => {
    const angle = (index * 360) / elements.length;
    element.style.transform = `rotateY(${angle}deg) translateZ(${radius}px)`;
    element.style.transition = 'transform 1s';
    element.style.transitionDelay = delayTime
      ? `${delayTime}s`
      : `${(elements.length - index) / 4}s`;
  });
};

// 应用变换
const applyTransform = (obj: HTMLElement): void => {
  // 限制 Y 轴旋转角度在 0-180 度之间
  if (tY.value > 180) tY.value = 180;
  if (tY.value < 0) tY.value = 0;

  // 应用旋转
  obj.style.transform = `rotateX(${-tY.value}deg) rotateY(${tX.value}deg)`;
};

// 控制旋转动画
const playSpin = (yes: boolean): void => {
  if (spinContainer.value) {
    spinContainer.value.style.animationPlayState = yes ? 'running' : 'paused';
  }
};

// 鼠标/触摸事件处理
const setupEventListeners = (): void => {
  if (!dragContainer.value) return;

  if (isMobileDevice()) {
    // 触摸事件
    const handleTouchStart = (e: TouchEvent): void => {
      if (timer) {
        clearInterval(timer);
        timer = null;
      }

      const touch = e.touches[0];
      sX.value = touch.clientX;
      sY.value = touch.clientY;

      const handleTouchMove = (moveEvent: TouchEvent): void => {
        const moveTouch = moveEvent.touches[0];
        nX.value = moveTouch.clientX;
        nY.value = moveTouch.clientY;

        desX.value = nX.value - sX.value;
        desY.value = nY.value - sY.value;
        tX.value += desX.value * 0.1;
        tY.value += desY.value * 0.1;

        if (dragContainer.value) {
          applyTransform(dragContainer.value);
        }

        sX.value = nX.value;
        sY.value = nY.value;
      };

      const handleTouchEnd = (): void => {
        document.removeEventListener('touchmove', handleTouchMove);
        document.removeEventListener('touchend', handleTouchEnd);

        timer = setInterval(() => {
          desX.value *= 0.95;
          desY.value *= 0.95;
          tX.value += desX.value * 0.1;
          tY.value += desY.value * 0.1;

          if (dragContainer.value) {
            applyTransform(dragContainer.value);
          }

          playSpin(false);

          if (Math.abs(desX.value) < 0.5 && Math.abs(desY.value) < 0.5) {
            if (timer) {
              clearInterval(timer);
              timer = null;
            }
            playSpin(true);
          }
        }, 17);
      };

      document.addEventListener('touchmove', handleTouchMove);
      document.addEventListener('touchend', handleTouchEnd);
    };

    document.addEventListener('touchstart', handleTouchStart);
  } else {
    // 鼠标事件
    const handleMouseDown = (e: MouseEvent): void => {
      if (timer) {
        clearInterval(timer);
        timer = null;
      }

      sX.value = e.clientX;
      sY.value = e.clientY;

      const handleMouseMove = (moveEvent: MouseEvent): void => {
        nX.value = moveEvent.clientX;
        nY.value = moveEvent.clientY;

        desX.value = nX.value - sX.value;
        desY.value = nY.value - sY.value;
        tX.value += desX.value * 0.1;
        tY.value += desY.value * 0.1;

        if (dragContainer.value) {
          applyTransform(dragContainer.value);
        }

        sX.value = nX.value;
        sY.value = nY.value;
      };

      const handleMouseUp = (): void => {
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);

        timer = setInterval(() => {
          desX.value *= 0.95;
          desY.value *= 0.95;
          tX.value += desX.value * 0.1;
          tY.value += desY.value * 0.1;

          if (dragContainer.value) {
            applyTransform(dragContainer.value);
          }

          playSpin(false);

          if (Math.abs(desX.value) < 0.5 && Math.abs(desY.value) < 0.5) {
            if (timer) {
              clearInterval(timer);
              timer = null;
            }
            playSpin(true);
          }
        }, 13);
      };

      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
    };

    // 鼠标滚轮事件
    const handleMouseWheel = (e: WheelEvent): void => {
      e.preventDefault();
      const d = e.deltaY ? e.deltaY / 20 : (e as any).wheelDelta / 20 || -e.detail;
      // 注意：这里需要调整 radius，但由于 radius 是常量，你可能需要将其改为 ref
      // init(1);
    };

    document.addEventListener('mousedown', handleMouseDown);
    document.addEventListener('wheel', handleMouseWheel, { passive: false });
  }
};

// 组件挂载时初始化
onMounted(() => {
  setTimeout(() => {
    init();
    setupEventListeners();
  }, 100);
});

// 组件卸载时清理
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
});
</script>

<style scoped>
.data_content {
  width: calc(100% - 40px);
  height: 1000px;
  margin-left: 15px;
  min-width: 1366px;
}

.data_content .data_c {
  width: 52%;
  height: 100%;
}

.data_content .data_c .data_c_1 {
  width: calc(100% - 50px);
  height: calc(70% - 15px);
  position: relative;
  margin-bottom: 35px;
  margin-left: 25px;
}

.data_content .data_c .data_c_1 .dzimg {
  width: 800px;
  height: 100%;
  margin: 0 auto;
  position: relative;
  background: url('../../../../assets/images/page1_3.jpg') no-repeat center;
  background-size: cover;
}

.data_content .data_c .data_c_1 .dzimg img {
  top: 25%;
  left: 50px;
  width: 500px;
  height: 600px;
  position: absolute;
  transition: transform 1s ease 1s;
  transform-style: preserve-3d;
  transform: rotateY(0deg) translateZ(240px);
}

.data_content .data_c .data_c_2 {
  width: calc(100% - 50px);
  height: calc(28% - 10px);
  border: 1px solid #20558b;
  position: relative;
  margin-left: 25px;
}

#drag-container,
#spin-container {
  position: absolute;
  display: flex;
  margin: auto;
  top: 48%;
  left: 45%;
  transform-style: preserve-3d;
  transform: rotateX(-10deg);
}

#drag-container img,
#drag-container video {
  transform-style: preserve-3d;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  line-height: 200px;
  font-size: 50px;
  text-align: center;
  box-shadow: 0 0 8px #fff;
  -webkit-box-reflect: below 10px linear-gradient(transparent, transparent, #0005);
}

#drag-container img:hover,
#drag-container video:hover {
  box-shadow: 0 0 15px #fffd;
  -webkit-box-reflect: below 10px linear-gradient(transparent, transparent, #0007);
}

#drag-container p {
  font-family: Serif;
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translate(-50%, -50%) rotateX(90deg);
  color: #fff;
}

#ground {
  width: 900px;
  height: 900px;
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translate(-50%, -50%) rotateX(90deg);
  background: -webkit-radial-gradient(center center, farthest-side, #9993, transparent);
}

#carousel-container {
  width: 100%;
  height: 100%;
}

/* 修复动画类 */
.spin-animation {
  animation: spin 10s infinite linear;
}

.spin-revert-animation {
  animation: spinRevert 10s infinite linear;
}

@keyframes spin {
  from {
    transform: rotateY(0deg);
  }

  to {
    transform: rotateY(360deg);
  }
}

@keyframes spinRevert {
  from {
    transform: rotateY(360deg);
  }

  to {
    transform: rotateY(0deg);
  }
}
</style>
